package com.gopay.checkorder.service.task.thread;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gopay.checkorder.service.CheckMainOrderAccount;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.exception.GopayException;

@Service("checkMainOrderAccountThread")
public class CheckMainOrderAccountThread {
    private final static Logger logger = LoggerFactory.getLogger("ORDER_ACCOUNT_SYNC");

    @Resource(name = "checkMainOrderAccount")
    private CheckMainOrderAccount checkMainOrderAccount;

    public void run(final List<CpsGenMainOrder> mainOrders) {
        if (mainOrders == null || mainOrders.size() == 0) {
            return;
        }

        final List<Callable<Boolean>> syncList = new ArrayList<Callable<Boolean>>();
        for (Iterator<CpsGenMainOrder> it = mainOrders.iterator(); it.hasNext();) {
            final CpsGenMainOrder mainOrder = it.next();

            syncList.add(new Callable<Boolean>() {

                @Override
                public Boolean call() {
                    boolean flag = false;

                    try {
                        flag = checkMainOrderAccount.sync(mainOrder);
                    } catch (GopayException e) {
                        logger.error("状态同步接口调用错误.orderId:" + mainOrder.getGopayOrderId()+",errCode="+e.getErrCode()+",errMsg="+e.getErrMsg());
                    }

                    return flag;
                }
            });
        }

        ExecutorService executorPoll = Executors.newFixedThreadPool(10);
        try {
            executorPoll.invokeAll(syncList, 10000, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            logger.error("executorPoll.invokeAll error.", e);
        }

        executorPoll.shutdown();
    }
}
